package consulinit

import (
	"common/database/config"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

type ConsulConfig struct {
	Host string
	Port int
}

func NewConsulClient(host string, port int) *ConsulConfig {
	return &ConsulConfig{
		Host: host,
		Port: port,
	}
}

func (c *ConsulConfig) RegisterConsul(name string, tags []string, port int, address string) {
	registration := api.AgentServiceRegistration{
		ID:      uuid.NewString(),
		Name:    name,
		Tags:    tags,
		Port:    port,
		Address: address,
	}
	file := `Service==` + name
	filter, _ := config.Consul.Agent().ServicesWithFilter(file)
	if len(filter) == 0 {
		err := config.Consul.Agent().ServiceRegister(&registration)
		if err != nil {
			zap.S().Error("服务注册失败")
			return
		} else {
			zap.S().Info("服务注册成功")
		}
	} else {
		zap.S().Info("服务已经注册过了")
	}
}
